package cn.antia.db;

import java.util.Map;

public abstract class AbstractSQLGene implements SQLGene{
    protected AbstractSQLGene() {
    }

    public String getRecordCountSQL(String sql) {
        sql = sql.trim();
    	String UPPERSQL = sql.toUpperCase();
    	//确定From位置
        int fromPosition = UPPERSQL.indexOf(" FROM ");
        return new StringBuilder(sql.substring(0, 6)).append(" count(*) as c ").append(sql.substring(fromPosition)).toString();
    }

    /**
     * ����order by �Ӿ�
     * @param sql   sql
     * @return  strings
     */
    protected String cutOrderBySql(String sql) {
        sql = sql.trim();
    	String UPPERSQL = sql.toUpperCase();
        while (UPPERSQL.indexOf(" ORDER  ") > 0) {
            UPPERSQL = UPPERSQL.replaceAll(" ORDER  ", " ORDER ");
        }
        if (UPPERSQL.indexOf(" ORDER BY ") > 0) {
            int p = UPPERSQL.lastIndexOf(" ORDER BY ");
            sql = sql.substring(0, p);
        }
        return sql;
    }
    
    public String composeSqlPage(String sql, String orderField, boolean isAsc, int page, int pageSize) {
        int start = (page - 1) * pageSize + 1;
        int end = start + pageSize - 1;
        return composeSql(sql, orderField, isAsc, start, end);
    }

    public JdbcSql composeSqlPage(JdbcSql sql, String orderField, boolean isAsc, int page, int pageSize) {
        int start = (page - 1) * pageSize + 1;
        int end = start + pageSize - 1;
        return composeSql(sql,orderField, isAsc, start, end);
    }

    public JdbcSql composeSql(JdbcSql sql, String orderField, boolean isAsc, int start, int end){
        sql.setSql(composeSql(sql.getSql(), orderField, isAsc, start, end));
        return sql;
    }

    public JdbcSql whereStatement(Map<String, Object> conditions, boolean isExact) {
        if (conditions == null || conditions.size() < 1) {
            return null;
        }
        JdbcSql jdbcSql = new JdbcSql();
        StringBuilder sql = new StringBuilder();
        Object[] values = new Object[conditions.size()];
        int i = 0;
        String opExpr = isExact ? "=" : "like";
        for (String field : conditions.keySet()) {
            if (sql.length() > 0) {
                sql.append(",");
            }
            sql.append(field).append(opExpr).append("?");
            values[i++] = conditions.get(field);
        }
        jdbcSql.setSql(sql.toString());
        jdbcSql.setValues(values);
        return jdbcSql;
    }

    public <T> T getMaxID(String table) {
        return null;
    }
}
